package handerls

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"xiao-hong-book/moderls"
	"xiao-hong-book/pkg"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")

	user := moderls.User{
		Tel:      tel,
		Password: pkg.Md5(password),
	}

	err := moderls.DB.Create(&user).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}

func List(c *gin.Context) {
	var book []moderls.Book

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	err := moderls.DB.Offset(offset).Limit(size).Count(&count).Find(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
	})
	return
}
